angular.module("driver").controller("MainCtrl", ['$scope', '$state','$meteor', '$ionicPopup', '$ionicModal',
	function($scope, $state, $meteor, $ionicPopup, $ionicModal){

		 $ionicModal.fromTemplateUrl('client/driver/views/arounds.ng.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
  });
  $scope.openModal = function() {
    $scope.modal.show();
    console.log("goodfun")
  };
  $scope.closeModal = function() {
    $scope.modal.hide();
  };
  //当我们用到模型时，清除它！
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });
  // 当隐藏的模型时执行动作
  $scope.$on('modal.hide', function() {
    // 执行动作
  });
  // 当移动模型时执行动作
  $scope.$on('modal.removed', function() {
    // 执行动作
  });
		
		$meteor.subscribe('new_message').then(function(subscriptionHandle){
			$scope.messages = $meteor.collection(Messages);
		});

		$scope.showMsg = function() {
			if ($scope.messages.length < 1) return;

			var msg = $scope.messages[0];
			var alertPopup = $ionicPopup.alert({
				title: msg.msg,
				template: '',
				okType: 'button-royal',
       		    okText: '确定'
			});
			alertPopup.then(function(res) {
				msg.read = true;
        		//$state.go('main.amap'r);
				//console.log('Thank you for not eating my delicious ice cream cone');
			});
		};

		$scope.isAdmin = function () {
			//console.log(this.userId)
			if (!Meteor.user()) return false;
			
			return Roles.userIsInRole(Meteor.user()._id, 'admin');
		};

		$scope.isDriver = function () {
			//console.log(this.userId)
			if (!Meteor.user()) return false;
			
			return Roles.userIsInRole(Meteor.user()._id, 'driver');
		};

		$scope.request = function () {
			console.log(Meteor.user());
			if (!Meteor.user()) {
      			//throw new Meteor.Error("未登录！", "必须先登录！");      			
				var alertPopup = $ionicPopup.alert({
					title: '温馨提示',
					template: '请您先登录！',
					okType: 'button-royal',
					okText: '确定'
				});
				alertPopup.then(function(res) {
					$state.go('account');
				});
				return false;
			}

			$meteor.call('addRequest').then(
				function (data) {
					$meteor.call('setRequest', Meteor.userId(), true);
					if ($state.current.name !== 'main.amap')
						$state.go('main.amap');
					//成功发送申请，不做处理，页面上面自动有派发订单的提示。
					//console.log('data = ', data);
				},
				function (err) {
					var alertPopup = $ionicPopup.alert({
						title: err.error,
						template: '<i>' + err.reason + '</i>',
						okType: 'button-royal',
						okText: '确定'
					});
				}
			);
		};

	    $meteor.subscribe('userStatus').then(function(subscriptionHandle) {
	      $scope.userStatus = $meteor.object(Meteor.users, {'_id': Meteor.userId()});
	    });
	    $meteor.subscribe('userData').then(function(subscriptionHandle) {
	      $scope.user = $meteor.object(Meteor.users, Meteor.userId());
	    });
	}
]);